package com.karashi.busloca;

import java.io.File;
import java.net.URL;
import java.text.MessageFormat;
import java.util.List;

import karachi109.com.busloca.R;

import org.apache.http.HttpStatus;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.karashi.html.HTMLParser;
import com.karashi.html.dao.Tag;

public class BusLocaActivity extends Activity implements OnClickListener {
	private BusLocaHttpClient mHttpClient;

	private static final String XPATH_CONTENTS_HOME = "//div[@id='contents'][last()]";
	private static final String SEARCH_RESULT = XPATH_CONTENTS_HOME + "/h3/img/@alt";

	private String REQUEST_URL = "http://loca.seibubus.co.jp/seibuloca/navi?VID=lsc&EID=nt&UKD=1&DSMK={0}&ASMK={1}";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		findViewById(R.id.button1).setOnClickListener(this);
		
		mHttpClient = new BusLocaHttpClient();

	}

	@Override
	protected void onResume() {
		TextView textView = (TextView) findViewById(R.id.test);

		// StringBuilder sb = get_1();

		// StringBuilder sb = get_2();

		// textView.setText(sb.toString());

		super.onResume();
	}

	@Override
	public void onClick(View v) {
		if (R.id.button1 == v.getId()) {
			EditText editText_1 = (EditText) findViewById(R.id.editText1);
			EditText editText_2 = (EditText) findViewById(R.id.editText2);

			StringBuilder sb = get_2(MessageFormat.format(REQUEST_URL, editText_1.getText().toString(), editText_2
					.getText().toString()));

			TextView textView = (TextView) findViewById(R.id.test);
			textView.setText(sb.toString());

		}
	}

	private StringBuilder get_2(String urlStr) {
		StringBuilder sb = new StringBuilder();

		// config cleaner properties

		HtmlCleaner htmlCleaner = new HtmlCleaner();

		CleanerProperties props = htmlCleaner.getProperties();
		props.setAllowHtmlInsideAttributes(false);
		props.setAllowMultiWordAttributes(true);
		props.setRecognizeUnicodeChars(true);
		props.setOmitComments(true);

		// create URL object
		try {
			URL url = new URL(urlStr);
			// get HTML page root node
			
			TagNode root = htmlCleaner.clean(url);

			Object[] nodes = root.evaluateXPath(SEARCH_RESULT);
			if (nodes.length > 0) {
				if ("検索エラー".equals(nodes[0].toString())) {
					sb.append(nodes[0].toString());
				} else {
					Object[] contentsHomeNodes = root.evaluateXPath(XPATH_CONTENTS_HOME);

					if (contentsHomeNodes.length > 0) {
						TagNode contentsHomeNode = (TagNode) contentsHomeNodes[0];

						/* 現在時刻取得 */
						sb.append(contentsHomeNode.evaluateXPath("//.[@class='src-time']/text()")[0].toString());
						sb.append("\n");

						/* ルート取得 */
						sb.append(contentsHomeNode.evaluateXPath("//.[@class='src-route']/./text()")[0].toString());
						sb.append("\n");

						/* 検索結果取得 */
						TagNode tableTag = (TagNode) contentsHomeNode.evaluateXPath("//.[@class='src-dia']/tbody")[0];
						sb.append("\n");

						List childTagList = tableTag.getChildTagList();

						int i = 0;
						for (Object object : childTagList) {
							TagNode tagNode = (TagNode) object;

							if (i == 0) {
								// テーブルヘッダ
								sb.append("### ヘッダ ###");
								sb.append("\n");
								for (Object tableHeader : tagNode.getChildTagList()) {
									sb.append(((TagNode) tableHeader).getText()).append(" : ");
								}
								sb.append("\n");
							} else {
								// 検索結果
								sb.append("### 結果" + i + " ###");
								sb.append("\n");
								for (Object tableHeader : tagNode.getChildTagList()) {
									sb.append(((TagNode) tableHeader).getText()).append(" : ");
								}
								
								// soonバスか判定
								if("soon".equals(tagNode.getChildTags()[0].getAttributeByName("class"))){
									sb.append("*");
								}
								
								sb.append("\n");

							}

							i++;
						}

						sb.append("\n");
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return sb;
	}

	private StringBuilder get_1() {
		StringBuilder sb = new StringBuilder();
		BusLocaHttpResponse response = mHttpClient
				.httpGet("http://loca.seibubus.co.jp/seibuloca/navi?VID=lsc&EID=nt&UKD=1&DSMK=120035&ASMK=120001");

		if (HttpStatus.SC_OK == response.getHttpStatusCode()) {

			HTMLParser parser = new HTMLParser(response.getContent());
			while (parser.hasNext()) {
				Tag tag = parser.next();

				sb.append(tag.toString() + "\n");
			}

		} else {

		}
		return sb;
	}
}